//
//  PBLoginViewController.m
//  Bus
//
//  Created by wangjiajia on 13-7-6.
//  Copyright (c) 2013年 wangjiajia. All rights reserved.
//

#import "PBLoginViewController.h"
#import "PBAppDelegate.h"
#import "WebServicesUtils.h"
#import "UIImage+UIImageExtras.h"
#import "LoginResult.h"
#import "ASIHTTPRequest.h"

#import "Tools.h"
#import "Config.h"
#import "JsonParser.h"
#import "LoginResult.h"
#import "MBProgressHUD.h"

//貌似不extern也没事
//extern int userId;
//extern NSString* userName;
@interface PBLoginViewController (){
    //定义一个私有全局的HUD，直接传给Request比较麻烦
    MBProgressHUD *hud;
    BOOL isCancleLogin;//是否取消登录
    ASIHTTPRequest* asiHTTPRequest;//发送的请求
}

@end

@implementation PBLoginViewController



- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
        
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    // 设置背景图片
    [self.view setBackgroundColor:[UIColor colorWithPatternImage:[UIImage imageNamed:@"bg_blue.jpg"]]];
    //遍历字体 找到字体名字
    //    NSArray *array = [UIFont familyNames];
    //    for  (NSString * familyname in array) {
    //        //NSLog(@"Family:%@\n" ,familyname);
    //        NSArray *fontnames = [UIFont fontNamesForFamilyName:familyname];
    //        for  (NSString *name in fontnames) {
    //            //NSLog(@"  Font Name:%@" ,name);
    //        }
    //    }
    
    //自定义字体 程序名（用Family则默认第一个Font,或用Font Name具体指定）
    //Family:叶根友特楷简体
    //Font Name:-
    self.appName.font=[UIFont fontWithName:@"-" size:60];
    self.remPass.font=[UIFont fontWithName:@"-" size:25];
    self.autoLogin.font=[UIFont fontWithName:@"-" size:25];
    //设置登录按钮背景
    UIImage *btnBg=[[UIImage imageNamed:@"LoginNormal"] resizableImageWithCapInsets:UIEdgeInsetsMake(10, 10, 10, 10)];
    [self.btnLogin setBackgroundImage:btnBg forState:UIControlStateNormal];
    
    //恢复switch状态
    [self.switchRemberPass setOn:[Config getSwitch_RememberPass_State] animated:YES];
    [self.switchAutoLogin setOn:[Config getSiwtch_AutoLogin_State] animated:YES];
    if([Config getSwitch_RememberPass_State]){
        self.txtUserName.text=[Config getUserName];
        self.txtPassword.text=[Config getPwd];
        if([Config getSiwtch_AutoLogin_State] )
        {
            
            if ([Tools isExistenceNetwork]) {
                //加这个判断，否则在没有网络时：
                //1、警告无网络连接 alert show
                //2、提示服务不可用 alert show 并且覆盖 1
                //3、点击确定 让2 关闭
                //4、1得以重见天日 alert show
                //5、点击确定 让1 关闭
                //即：3次show 2次关闭 !体验不好！
                
                //自动登录,登录太快了! 考虑给3秒钟纠结时间
                //发起异步请求
                asiHTTPRequest=[WebServicesUtils checkLogin:_txtUserName.text andPass:_txtPassword.text withDelegate:self];
                //全局hud初始化
                if(!hud)
                {
                    hud=[[MBProgressHUD alloc] initWithView:self.view];
                    //添加一个透明的矩形按钮，监听“点击取消登录”
                    UIButton* cancleButton=[[UIButton alloc] initWithFrame:CGRectMake(0, 0, 120, 120)];
                    cancleButton.backgroundColor=[UIColor clearColor];
                    cancleButton.center=self.view.center;
                    [cancleButton addTarget:self action:@selector(cancleLogin) forControlEvents:UIControlEventTouchUpInside];
                    [hud addSubview:cancleButton];
                }
                [Tools showHUD:@"正在登陆中..." andView:self.view andHUD:hud];
                //                //NSLog(@"%@",NSStringFromCGSize(hud.minSize));
            }
        }
    }
}



- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

//- (void)dealloc {
//    [_btnLogin release];
//    [_switchAutoLogin release];
//    [_switchRemberPass release];
//    [_txtUserName release];
//    [_txtPassword release];
//    [super dealloc];
//}

-(void)viewDidUnload{
    [super viewDidUnload];
    //调试技巧
#if DEBUG_STATUS
    //NSLog(@"LoginView viewDidUnload");
#endif
}

#pragma mark - 自定义函数
- (IBAction)checkLogin:(id)sender {
    
    /*
     LoginResult * _loginResult=[WebServicesUtils checkLogin:_txtUserName.text andPass:_txtPassword.text];
     
     
     //跳转到主页
     if(_loginResult.loginRet==1){
     [(PBAppDelegate *)[UIApplication sharedApplication].delegate goMainView];
     }else{
     UIAlertView *alert=  [[UIAlertView alloc] initWithTitle:@"提示" message:_loginResult.loginMsg delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil] ;
     
     [alert show];
     
     }*/
    isCancleLogin=NO;//设置为不取消登录。
    
    //发起异步请求
    asiHTTPRequest= [WebServicesUtils checkLogin:_txtUserName.text andPass:_txtPassword.text withDelegate:self];
    //全局hud初始化
    if(!hud)
    {
        hud=[[MBProgressHUD alloc] initWithView:self.view];
        //添加一个透明的矩形按钮，监听“点击取消登录”
        UIButton* cancleButton=[[UIButton alloc] initWithFrame:CGRectMake(0, 0, 110, 110)];
        cancleButton.backgroundColor=[UIColor clearColor];//默认颜色就是透明色
        cancleButton.center=self.view.center;
        [cancleButton addTarget:self action:@selector(cancleLogin) forControlEvents:UIControlEventTouchUpInside];
        [hud addSubview:cancleButton];
    }
    [Tools showHUD:@"正在登陆中..." andView:self.view andHUD:hud];
    
    
}
//模拟取消登录,请求其实没有结束!
//为了让请求也结束,需要将Request返回
-(void)cancleLogin{
    [Tools toastNotification:@"您取消了登录!" andView:self.view andLoading:NO andIsBottom:NO];
    //NSLog(@"取消登录!");
    isCancleLogin=YES;
    if (hud) {
        [hud hide:YES];
    }
    if (asiHTTPRequest) {
        //NSLog(@"取消登录请求!");
        
        //[request cancel]取消的请求默认都会按请求失败处理，并调用请求失败delegate。
        //[asiHTTPRequest cancel];
        //如果不想调用delegate方法，则设置：[ request clearDelegatesAndCancel];
        [asiHTTPRequest clearDelegatesAndCancel];
    }
}

//处理请求结果
-(void)requestFinished:(ASIHTTPRequest *)request{
    
    //请求自带了hud，可以把hud赋值进去，但是在WebServicesUtils中还要把当前view传递过去，比较麻烦
    //当然代理即为自己，可以强制转换
    //    if( request.hud){
    //        [request.hud hide:YES];
    //    }
    if(hud){
        [hud hide:YES];
    }
    
    if(isCancleLogin){
        //NSLog(@"请求结束，但由于取消登录，return");
        return;//取消登录，则不处理结果
    }
    //返回的字符串可能是 当前服务暂时不可用
    NSString * responseStr=[request responseString];
    //NSLog(@"%@",responseStr);
    //模拟服务请求响应成功，但是返回不可用提示 看看loginResult解析为啥 应该为nil?或则不是nil但是字段均为空？调试发现为:loginResult.loginRet=0 loginResult.loginMsg=nil
    //responseStr=@"<HTML><title>Sorry</title><body>Service Unavailable</body></HTML>";
    
    LoginResult * loginResult= [JsonParser parseAsLoginResult:responseStr];
    if(loginResult.loginRet==1||loginResult.loginRet==3){//跳转主页
        
        //处理 记住密码，自动登陆。用户名默认记住。
        //todo:如果自动登录，考虑到可能切换用户，应该可以取消登录。
        if(self.switchRemberPass.isOn){
            //保存用户名密码
            [Config saveUserName:self.txtUserName.text andPass:self.txtPassword.text];
        }
        //保存切换状态
        [Config saveSiwtch_State:self.switchRemberPass.isOn andLogin:self.switchAutoLogin.isOn];
        
        
        PBAppDelegate* pbAppDelegate=(PBAppDelegate *)[UIApplication sharedApplication].delegate;
        //保存全局的用户名和密码
        userId=loginResult.userId;
        userName=loginResult.userName;
        //NSLog(@">>>登陆成功，userId=%d；userName=%@",userId,userName);
        //转到主页
        [pbAppDelegate goMainView:loginResult.loginRet];
        
        self.view =nil;//算手动销毁？
    }else{
        NSString* alertInfo=@"服务器接口不可用!";
        
        if(loginResult.loginMsg){
            alertInfo=loginResult.loginMsg;
        }
        
        UIAlertView *alert=  [[UIAlertView alloc] initWithTitle:@"提示" message:alertInfo delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil] ;
        
        [alert show];
        
    }
    
    
}
//请求失败
-(void)requestFailed:(ASIHTTPRequest *)request{
    if(hud){
        [hud hide:YES];
    }
    if(isCancleLogin){
        //NSLog(@"请求失败，但由于取消登录，return");
        return;//取消登录，则不处理结果
    }
#if DEBUG_STATUS
    //NSLog(@"处理请求失败");
#endif
    //可以换成友好的顶部弹出提示。考虑到这是第一个界面，没有啥数据，可以用alert弹窗 比较显眼些
    UIAlertView *alert=  [[UIAlertView alloc] initWithTitle:@"提示" message:@"网络请求错误,服务不可用!" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil] ;
    
    [alert show];
}
- (IBAction)resignFirst:(id)sender {
    //NSLog(@"放弃第一响应！");
    [self.view endEditing:YES];
}
@end
